<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useForm } from '@/hooks/web/useForm'
import { ElButton, ElInput, ElLink, ElMessage } from 'element-plus'
import { UserType } from '@/api/login/types'
import { registerApi, phoneApi } from '@/api/login'
const loading = ref(false);
const code_text = ref("获取验证码");
// const code_disabled = ref(false);
const code_loading = ref(false);
const code_timer = ref<number | null | undefined>();

const emit = defineEmits(['to-login'])

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const { t } = useI18n()
const rules = {
  username: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[1][3,4,5,7,8,9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur', },
    { pattern: /^[A-Za-z0-9]+$/, message: '密码只能包含英文字母和数字', trigger: 'blur' }
  ],
  again_password: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '密码只能包含英文字母和数字', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur', },
  ],
  chechked: [
    { required: true, message: '请先同意用户协议', trigger: 'blur', },
  ],
}
const schema = reactive<FormSchema[]>([
  {
    field: 'Login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <div>
            <h2 class="login-text2  w-[100%]">香城英才网</h2>
            {/* <h2 class="login-text3  w-[100%]">Human Resources Management System</h2> */}
          </div>
        }
      }
    }
  },
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold  w-[100%]">{t('login.register')}</h2>
        }
      }
    }
  },
  {
    field: 'username',
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: "请输入手机号",
      type: 'string',
      maxlength: 11
    }
  },
  {
    field: 'code',
    label: "",
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div class="flex w-[100%] phone_code_phone" >
                <el-form class="demo-ruleForm w-[100%]">
                  <el-form-item prop="code" >
                    <ElInput placeholder='请输入验证码' v-model={data.code} type='number' ></ElInput></el-form-item>
                </el-form>
                <div class="phone_code_span" onClick={getCode}>{code_text.value}</div>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'password',
    label: "",
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      strength: false,
      placeholder: "请输入用户密码"
    }
  },
  {
    field: 'again_password',
    label: "",
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      strength: false,
      placeholder: "请再次输入密码"
    }
  },
  {
    field: 'chechked',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <el-form class="demo-ruleForm w-[100%]">
                  <el-form-item prop="chechked" >
                    <el-checkbox-group v-model={data.chechked}>
                      <el-checkbox>同意<span style="color:#2F6CBC">《用户注册协议》</span></el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'register',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <ElButton
                  type="primary"
                  class="w-[100%]"
                  loading={loading.value}
                  onClick={loginRegister}
                >
                  {t('login.register')}
                </ElButton>
              </div>
              <div class="w-[100%] mt-15px flex justify-center items-center">
                <ElLink type="primary" underline={false} onClick={toLogin}>已有账号?去登录</ElLink>
              </div>
            </>
          )
        }
      }
    }
  }
])



const toLogin = () => {
  emit('to-login')
}
const loginRegister = async () => {
  const formRef = await getElFormExpose()
  formRef?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        toLogin()
      } finally {
        loading.value = false
      }
    }
  })
}

const getCode = async () => {
  const formRef = await getElFormExpose()
  formRef?.validateField("username", (valid: any) => {
    if (valid) {
      if (code_text.value == "重新获取" || code_text.value == "获取验证码") {
        phoneApi_()
        countdown();
      } else {
        return
      }
    }
  });
};

/** 倒计时 */
const countdown = () => {
  let second = 60; // 默认时间
  code_loading.value = false; // 取消加载
  // code_disabled.value = true; // 禁用按钮
  code_text.value = `${second}秒`; // 按钮文本
  // 判断是否存在定时器，存在则先清除
  if (code_timer.value) {
    clearInterval(code_timer.value);
  }
  // 开启定时器
  code_timer.value = Number(
    setInterval(() => {
      second--;
      code_text.value = `${second}秒`; // 按钮文本
      if (second <= 0) {
        code_text.value = `重新获取`; // 按钮文本
        // code_disabled.value = false; // 启用按钮
        clearInterval(code_timer.value as number); // 清除倒计时
      }
    }, 1000)
  );
};
// 获取手机验证码
const phoneApi_ = async () => {
  const formData = await getFormData<UserType>()
  let params = {
    phonenumber: formData.username
  }
  await phoneApi(params).then((res: any) => {
    ElMessage.success(res.msg)
  }).catch((res: any) => {
    ElMessage.error(res.msg)
  })
}
</script>

<template>
  <Form :schema="schema" :rules="rules" label-position="top" hide-required-asterisk size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)" @register="formRegister" />
</template>
<style lang="less" scoped>
.phone_code_phone {
  position: relative;

  .phone_code_span {
    position: absolute;
    top: 0;
    right: 20px;
    color: #2F6CBC;
  }

}
</style>
